package com.wtf.handler;

import org.rpc.pojo.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * desc:
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 11/10/2020
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext channelHandlerContext;

    private RpcRequest param;

    private String result;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.channelHandlerContext = ctx;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     * @param ctx ChannelHandlerContext
     * @param msg 参数
     * @throws Exception 异常
     */
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        this.result = msg.toString();
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     * @return 结果
     * @throws Exception 异常
     */
    @Override
    public synchronized Object call() throws Exception {
        channelHandlerContext.writeAndFlush(param);
        wait();
        return result;
    }

    public void setParam(RpcRequest param) {
        this.param = param;
    }
}
